#pragma once

#include <iostream>
#include <string>
#include <unordered_map>
#include <functional>
#include "TcpServer.hpp"
#include "HttpProtocol.hpp"

using namespace TcpServerMoudle;

using http_handler_t = std::function<void(HttpReauest&, HttpResponse&)>;

class HttpServer
{
public:
    HttpServer(int port)
        : _tsvr(std::make_unique<TcpServer>(port))
    {
    }

    void Resgiter(std::string funcname, http_handler_t func)
    {
        _route[funcname] = func;
    }

    bool SafeCheck(const std::string &service)
    {
        auto iter = _route.find(service);
        return iter != _route.end();
    }

    void Start()
    {
        _tsvr->InitServer([this](SockPtr sockfd, InetAddr client)
                          { return this->HandlerHttpRequset(sockfd, client); });
        _tsvr->Loop();
    }

    // 处理http的入口
    bool HandlerHttpRequset(SockPtr sockfd, InetAddr client)
    {
        LOG(LogLevel::DEBUG) << "HttpServer: get a new client: " << sockfd->Fd() << " addr info: " << client.Addr();
        std::string http_request;
        sockfd->Recv(&http_request);

        HttpReauest req;
        req.Deserialize(http_request);
        HttpResponse resp;
        // 请求应该被分成两类： 1.请求一般的静态资源 2. 提交参数，携带参数，需要我们进行交互设置
        if(req.IsHasArgs())
        {
            // 2. 提交参数，携带参数，需要我们进行交互设置
            std::string service = req.Path();
            if(SafeCheck(service))
                _route[service](req, resp);      // /login
            else 
                resp.Build(req);  // debug
        }
        else if(req.Islog())
        {
            if(req.Uri() == "/log.html" || req.Uri() == "/register.html") _route[req.Uri()](req, resp);
            else resp.Build(req);
        }
        else
        {
            if(req.Uri() == "/log.html" || req.Uri() == "/register.html") _route[req.Uri()](req, resp);
            else if(req.Uri() == "/index.html") resp.Build(req);
            else _route["/log.html"](req, resp);
        }
        std::string resp_str;
        resp.Serialize(&resp_str);
        sockfd->Send(resp_str);
        return true;

        // std::cout << http_request;
        // 读取请求，对请求进行分析处理 --> 文本处理！
        // 1. 读取请求的完整性 --- 暂时不做
        // 2. 完整 http 反序列化 http response 序列化
        // demo 1 : 直接返回一个固定的内容
        // std::string status_line = "HTTP/1.1 200 OK" + Sep + BlankLine;

        // 直接返回一个html网页
        // std::string body = "<!DOCTYPE html>\
        // <html lang=\"zh-CN\"><head><meta charset=\"UTF-8\"><meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"><title>Hello World</title> <style>body {display: flex;justify-content: center;align-items: center;height: 100vh;margin: 0;font-family: Arial, sans-serif;background-color: #f0f0f0;}h1 {color: #333;}</style></head><body><h1>Hello World</h1></body></html>";
        // std::string httpresponse = status_line + body;
        // sockfd->Send(httpresponse);
        // return true;
    }

    ~HttpServer()
    {
    }

private:
    std::unique_ptr<TcpServer> _tsvr;
    std::unordered_map<std::string, http_handler_t> _route;   // 功能路由
};